package com.neuronrobotics.opengl.scene;



import java.util.Arrays;

import android.opengl.GLES20;

public class SimpleMutableBoxNode extends ArrayShapeNode {
		
	private float[] maxes = new float[3],mins = new float[3];
	
	public static SimpleMutableBoxNode getSimpleMutableBox(GLHandles handles, float[] max, float[] min){
				
		float[] coords = getCoords(max,min);	
		
		return new SimpleMutableBoxNode(handles, max,min, coords );
	}
	
	private static float[] getCoords(float[] max, float[] min) {
		float[] distinctPoints = getPoints(max,min);	
		float[] result = new float[12*2*3];
		int ct =0;
		for(int i=0;i<7;i++){
			for(int j=i+1;j<8;j++){
				if(checkMatch(distinctPoints,i,j)){
					result[ct++]=distinctPoints[i*3];
					result[ct++]=distinctPoints[i*3+1];
					result[ct++]=distinctPoints[i*3+2];
					result[ct++]=distinctPoints[j*3];
					result[ct++]=distinctPoints[j*3+1];
					result[ct++]=distinctPoints[j*3+2];
				}
			}
		}
		
		return result;
	}

	private static boolean checkMatch(float[] distinctPoints, int i, int j) {
		int ct=0;
		ct+=distinctPoints[3*i]==distinctPoints[3*j]?1:0;
		ct+=distinctPoints[3*i+1]==distinctPoints[3*j+1]?1:0;
		ct+=distinctPoints[3*i+2]==distinctPoints[3*j+2]?1:0;				
		return ct==2;
	}

	private static float[] getPoints(float[] max, float[] min) {
		float[] result = new float[8*3];
		
		for(int i=0;i<8;i++){
			if(i>=4) result[i*3]=max[0];
			else result[i*3]=min[0];
		}
		for(int i=0;i<8;i++){
			if((i%4)>=2) result[i*3+1]=max[1];
			else result[i*3+1]=min[1];
		}
		for(int i=0;i<8;i++){
			if((i%2)>=1) result[i*3+2]=max[2];
			else result[i*3+2]=min[2];
		}		
		
		return result;
	}

	private SimpleMutableBoxNode(GLHandles handles, float[] max, float[] min, float[] coords){
		super(handles, coords, new float[]{0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0}, GLES20.GL_LINES);
		maxes = Arrays.copyOf(max, 3);
		mins = Arrays.copyOf(min, 3);
	}
	
	public void setMax(float x, float y, float z){
		this.maxes[0] = x;
		this.maxes[1] = y;
		this.maxes[2] = z;
		this.coordinates = getCoords(maxes, mins);
		
		initialize();
	}
	
	public void setMin(float x, float y, float z){
		this.mins[0] = x;
		this.mins[1] = y;
		this.mins[2] = z;
		this.coordinates = getCoords(maxes, mins);		
		initialize();
	}

				
}
